package com.cndw.kungfu.ext;

import java.io.InputStreamReader;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

import com.cndw.kungfu.config.Constants;
import com.cndw.kungfu.config.ConstantsConfig;

public class LanguageLib {

	private static Properties properties;

	static {
		load();
	}

	public static void load() {
		try {
			Properties temp = new Properties();
			InputStreamReader input = new InputStreamReader(LanguageLib.class.getResourceAsStream("/" + ConstantsConfig.getLocaleResource() + Constants.LANGUAGE_FILE),
					"UTF-8");
			temp.load(input);
			input.close();
			properties = temp;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String get(String key) {
		if (properties == null)
			load();
		if (properties != null) {
			String property = properties.getProperty(key);
			return property;
		}
		return "";
	}

	public static String get(String key, Object... values) {
		String source = LanguageLib.get(key);

		if (source == null || values == null || values.length < 0)
			return "";
		return LanguageLib.format(source, values);
	}

	private static String format(String str, Object... args) {
		if (StringUtils.isBlank(str)) {
			return "";
		}

		if (args.length == 0) {
			return str;
		}
		String result = str;
		Pattern p = Pattern.compile("\\{(\\d+)\\}");
		Matcher m = p.matcher(str);
		while (m.find()) {
			int index = Integer.parseInt(m.group(1));
			if (index < args.length) {
				result = result.replace(m.group(), args[index].toString());
			}
		}
		return result;
	}
	
	public static void clear(){
		load();
	}

}
